package org.boyan.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ExcelUtils {

    //判断excel文件的文件后缀，是xls还是xlsx
    public static boolean judegExcelEdition(String fileName) {
        if (fileName.matches("^.+\\.(?i)(xls)$")) {
            return false;
        } else {
            return true;
        }
    }

    //单纯的file文件去获取Workbook
    public static Workbook getWorkBook(File file){
        String fileName=file.getName();
        InputStream in = null;
        Workbook workbook = null;
        try {
            in = new FileInputStream(file);
            if (judegExcelEdition(fileName)) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  workbook;
    }

    //前端返回的multipartFile获取Workbook
    public static Workbook getWorkBook(MultipartFile multipartFile){
        String fileName = multipartFile.getOriginalFilename();
        InputStream in = null;
        Workbook workbook = null;
        try {
            in = multipartFile.getInputStream();
            if (judegExcelEdition(fileName)) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  workbook;
    }
}
